package com.zahb.qadx.ui.activity.videopage;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.google.gson.Gson;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.zahb.qadx.R;
import com.zahb.qadx.base.BaseActivity;
import com.zahb.qadx.model.CommonData;
import com.zahb.qadx.model.JsonRootMicroVideoBean;
import com.zahb.qadx.model.MicroVideoData;
import com.zahb.qadx.net.RetrofitService;
import com.zahb.qadx.util.ClickCheck;
import com.zahb.qadx.util.CompatHelper;
import com.zahb.qadx.util.DisplayUtil;
import com.zahb.qadx.util.ImageLoaderKt;
import com.zahb.qadx.util.Tips;

import org.jetbrains.annotations.NotNull;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

//搜索
public class SearchActivity extends BaseActivity implements OnItemClickListener, OnRefreshLoadMoreListener {

    @BindView(R.id.return_to_cancel)
    ImageView returnToCancel;
    @BindView(R.id.search_symbol)
    TextView searchSymbol;
    @BindView(R.id.position_id)
    ImageView positionId;
    @BindView(R.id.again)
    ImageView again;
    @BindView(R.id.search_content)
    EditText searchContent;
    @BindView(R.id.search)
    RelativeLayout search;

    private static final String KEY_ICON = "mKeyIcon";
    private static final String KEY_NAME = "mKeyName";
    @BindView(R.id.top_search)
    RecyclerView recyclerView;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.popular_collection)
    RecyclerView popularCollection;
    @BindView(R.id.popular_layout)
    RelativeLayout popularLayout;
    private int mPage=1;
    private String name;
    private int[] mIconIds = {
            R.drawable.ic_answer_exercises_everyday,
            R.drawable.ic_answer_exercises_weekly,
            R.drawable.ic_answer_exercises_special};
    private String[] mNames = {"山东一蛋糕店房发上爆炸", "北京一蛋糕店房发上爆炸", "田径一蛋糕店房发上爆炸"};
    //    private BaseQuickAdapter<CartInfoBean, BaseViewHolder> mAdapter;
    private BaseQuickAdapter<Map<String, Object>, BaseViewHolder> mAdapter;
    private TaskAdapter mTaskAdapter;
    private JsonRootMicroVideoBean classifiedListDataBean;
    //实时监听数据
    private  TextWatcher watcher;
    private CommonData<MicroVideoData.MicroVideoBean> microVideoBeans;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mTopBarContainer.setVisibility(View.GONE);//隐藏统一导航栏
        classifiedListDataBean= (JsonRootMicroVideoBean)getIntent().getSerializableExtra("jsonRootMicroVideoBean");
        for (int i = 0; i < mIconIds.length; i++) {
            Map<String, Object> item = new HashMap<>();
            item.put(KEY_NAME, mNames[i]);
            mAdapter.addData(item);
        }

    }

    @Override
    protected int getLayout() {
        return R.layout.activity_search;
    }

    @Override
    protected void onStart() {
        super.onStart();
        //实时监听数据
         watcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                Log.d("实时数据", s.toString());
                name = s.toString();
                mPage=1;
                getTaskList(name);
                if (s.toString().equals("")){
                    again.setVisibility(View.GONE);
                }else {
                    again.setVisibility(View.VISIBLE);
                }
            }
        };
        searchContent.addTextChangedListener(watcher);
    }

    @Override
    protected void initViews() {
        mUnbinder = ButterKnife.bind(this);
        refreshLayout.setOnRefreshLoadMoreListener(this);
        refreshLayout.setEnableLoadMoreWhenContentNotFull(false);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mTaskAdapter = new TaskAdapter(R.layout.item_list_video);
        View emptyView = View.inflate(getContext(), R.layout.empty_layout, null);
        emptyView.setVisibility(View.VISIBLE);
        mTaskAdapter.setEmptyView(emptyView);
        mTaskAdapter.setUseEmpty(true);
        recyclerView.setAdapter(mTaskAdapter);
        mTaskAdapter.setOnItemClickListener(this);
        int divider = DisplayUtil.dip2px(10f);
        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                if (parent.getAdapter() == null) return;
                outRect.set(0, 0, 0, divider);
            }
        });


        //热门
        popularCollection.setLayoutManager(new LinearLayoutManager(getContext()));
        popularCollection.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                outRect.set(0, 0, 0, DisplayUtil.dip2px(16f));
            }
        });
        mAdapter = new BaseQuickAdapter<Map<String, Object>, BaseViewHolder>(R.layout.popular_search_layout) {
            @Override
            protected void convert(@NotNull BaseViewHolder baseViewHolder, Map<String, Object> item) {
//                int iconId = (int) item.get(KEY_ICON);
//                baseViewHolder.setBackgroundResource(R.id.iv_icon, iconId);
                String name = (String) item.get(KEY_NAME);
                baseViewHolder.setText(R.id.top_search_titles, name);
                baseViewHolder.findView(R.id.top_search_titles).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        searchContent.setText(item.get(KEY_NAME) + "");
//                        getTaskList( item.get(KEY_NAME)+"");
                    }
                });
            }
        };

        popularCollection.setAdapter(mAdapter);

    }

    @Override
    public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (ClickCheck.isFastClick()) return;

        Intent intent = new Intent(getActivity(), FlipVideoActivity.class);
//        Intent intent = new Intent(getActivity(), VideoRecyclerViewActivity.class);
        intent.putExtra("bean", microVideoBeans);

        intent.putExtra("mTaskAdapter", mTaskAdapter.getItem(position));
        intent.putExtra("value", position);
        startActivity(intent);
        getActivity().overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);

    }

    @Override
    protected int getTitleStringRes() {
        return R.string.micro_video_list;
    }

    @OnClick({R.id.return_to_cancel, R.id.search_symbol, R.id.again, R.id.search_content, R.id.search})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.return_to_cancel://返回
                finish();
                break;
            case R.id.search_symbol://搜索
                getTaskList(name);
                break;
            case R.id.position_id:
                break;
            case R.id.again://重新
                searchContent.setText("");
//                popularLayout.setVisibility(View.VISIBLE);
                break;
            case R.id.search_content://输入框

                break;
            case R.id.search:
                break;
        }
    }

    //     网络请求
    private void getTaskList(String name) {

        if (name.equals("")) {
            return;
        }
        popularLayout.setVisibility(View.GONE);
        Map<String, Object> params = new HashMap<>();
        params.put("categoryId", classifiedListDataBean.getData().get(0).getId());
        params.put("name", name);
        params.put("pageNum", mPage);
        params.put("pageSize", 10);
        Gson mGson = new Gson();
        String json = mGson.toJson(params);
        Log.e("json", json);
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);
        addDisposable(RetrofitService.getNetService()
                .getStudentsGetAListOfMicroVideos(body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    refreshLayout.finishRefresh();
                    refreshLayout.finishLoadMore(1000);
                    if (response.getStatusCode() == 200) {
                        if (response.getData() != null) {
                            if (mPage == 1) {
                                mTaskAdapter.setList(response.getData().getList());
                                microVideoBeans = response.getData();
                            } else {
                                mTaskAdapter.addData(response.getData().getList());
                                microVideoBeans.getList().addAll(response.getData().getList());

                            }
                        } else {
                            showBindToast("已经到底了");
                        }

                    } else {
                        showBindToast(response.getErrorInfo());
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    refreshLayout.finishRefresh();
                    Tips.RequestError(getActivity());
                    refreshLayout.finishLoadMore(1000);

                }));


    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        mPage++;
        getTaskList(name);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        mPage = 1;
        getTaskList(name);
    }

    private static class TaskAdapter extends BaseQuickAdapter<MicroVideoData.MicroVideoBean, BaseViewHolder> {

        TaskAdapter(int layoutResId) {
            super(layoutResId);
        }

        @Override
        protected void convert(@NotNull BaseViewHolder baseViewHolder, MicroVideoData.MicroVideoBean task) {
            ImageLoaderKt.loadImageSameCorners(baseViewHolder.getView(R.id.video_chart),
                    CompatHelper.isEmpty(task.getCoverImage()) ? "20200914/1600056121587689.jpg" : task.getCoverImage(), 5f);
            baseViewHolder.setText(R.id.tv_sub_title, task.getName());
            baseViewHolder.setText(R.id.playVolume, task.getPlayVolume_Str() );
            baseViewHolder.setText(R.id.duration, "视频时长：" + millisecondsToMinuteSecondStr(task.getDuration()));


        }

        // 将毫秒转为分钟：秒
        private static String millisecondsToMinuteSecondStr(int ms) {
            int seconds = (int) ms;
            String result = "";
            int min, second;
            min = seconds / 60;
            second = seconds - min * 60;

            if (min < 10) {
                result += "0" + min + ":";
            } else {
                result += min + ":";
            }
            if (second < 10) {
                result += "0" + second;
            } else {
                result += second;
            }
            return result;
        }

    }
    public static void actionStart(Context context, JsonRootMicroVideoBean jsonRootMicroVideoBean) {
        Intent intent = new Intent(context, SearchActivity.class);
        Bundle args = new Bundle();
        args.putSerializable("jsonRootMicroVideoBean", jsonRootMicroVideoBean);
        intent.putExtras(args);
        context.startActivity(intent);

    }

}
